import { useCallback } from "react";
import { userApi } from "@/api";
import { useAppStore } from "@/stores";

export const useAuth = () => {
  const { user, token, setAuth, logout } = useAppStore();

  const isAuthenticated = !!token;

  const login = useCallback(
    async (data: { username: string; password: string }) => {
      const { data: authData } = await userApi.login(data);
      setAuth(authData);
      return authData;
    },
    [setAuth]
  );

  const getProfile = useCallback(async () => {
    try {
      const { data: profile } = await userApi.profile();
      return profile;
    } catch (error) {
      logout();
      return null;
    }
  }, [logout]);

  return {
    isAuthenticated,
    login,
    getProfile,
    user,
    logout,
  };
};
